#include "TaskThread.h"

TaskThread::TaskThread(long hwnd, std::wstring path)
    : m_bRunning(false), m_bindWnd((HWND)hwnd)
{
    long lRet;
    m_wudong.SetPath(path.c_str(), &lRet);
}

bool TaskThread::start()
{
    if (m_bRunning)
    {
        return false;
    }
    long lRet;
    m_wudong.BindWindow((long)m_bindWnd, L"dx2", L"normal", L"normal", 0, &lRet);
    m_wudong.SetWindowSize((long)m_bindWnd, 950, 739, &lRet);
    if (lRet != 1)
    {
        return false;
    }
    m_bRunning = true;
    m_thread = std::thread(&TaskThread::run, this);
    m_thread.detach();
    return true;
}
void TaskThread::stop()
{
    if (!m_bRunning)
    {
        return;
    }
    m_bRunning = false;
    m_cv.notify_one();
    m_thread.join();
}
void TaskThread::addTask(std::shared_ptr<BaseTask> task)
{
    m_mutex.lock();
    m_tasks.push_back(task);
    m_mutex.unlock();
    m_cv.notify_one();
}
void TaskThread::run()
{
    std::shared_ptr<BaseTask> currTask = nullptr;

    while (m_bRunning)
    {
        if (currTask == nullptr)
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_cv.wait(lock, [this]()
                      { return (!m_tasks.empty() || !m_bRunning); });
            if (!m_bRunning)
                return;

            currTask = m_tasks.front();
            currTask->initialize(this);
        }
        if (currTask->run())
        {
            // 任务执行结束，从队列中移除。执行下个任务
            m_mutex.lock();
            m_tasks.erase(m_tasks.begin());
            currTask = nullptr;
            m_mutex.unlock();
        }
    }
}
